/**
 * Created by gongxun on 16/11/23.
 */

var KwxTableEndLayer = GameCCSBase.extend({
    Panel_players : null,
    mRoundEndInfo : null,
    mHuangzhuangPeihuSeats : null,
    mCardWidth : null,
    Panel_piao : null,
    ctor: function () {
        this._super();
        this.loadCocostudio("res/ccs/KwxTableEnd.json");
        this.Panel_players = [];
        // this.mCardWidth = 34;
        this.mCardWidth = ((840 * mo.gameSize.x / 960) - 90 - 350) / 14;

        this.Panel_piao = mo.seekWidgetByName(this.ccsNode, "Panel_piao");

        //确定
        mo.seekWidgetByName(this.ccsNode, "Button_ok").addTouchEventListener(function (sender, type) {
            if (mo.gameHelper.getIsTouchEnd(type)) {
                if (mo.kwxTable.mPlayerType == 0){
                    //录像x
                    this.setVisible(false);
                    mo.kwxTable.mKwxReplayLayer.onPlayEnd();
                }else{
                    if (mo.kwxTable.mKwxJuEndedEventkwx == null){
                        mo.gameMsgManager.sendGameReadyRequestkwx(mo.kwxCardHelper.getUseSelectPiao());
                    }else{
                        //打完了 显示大结算
                        mo.kwxTable.mKwxJuEndedEventkwx.setVisible(true);
                        this.setVisible(false);
                    }
                }
            }
        }, this);

        //关闭
        mo.seekWidgetByName(this.ccsNode, "Button_close").addTouchEventListener(function (sender, type) {
            if (mo.gameHelper.getIsTouchEnd(type)) {
                //录像x
                this.setVisible(false);
                mo.kwxTable.mKwxReplayLayer.onPlayEnd();
            }
        }, this);

        //分享
        mo.seekWidgetByName(this.ccsNode, "Button_share").addTouchEventListener(function (sender, type) {
            if (mo.gameHelper.getIsTouchEnd(type)) {
                if (mo.kwxTable.mPlayerType == 1){
                    mo.kwxTable.mReplayId = mo.kwxTableStatus.mTableStatus.ReplayId;
                }
                //录像
                mo.kwxTable.onShareReplay();
            }
        }, this);

        //飘
        for (var i = 0; i < 3; i++){
            var Panel_piao = mo.seekWidgetByName(this.Panel_piao, "Panel_piao" + i);
            Panel_piao.setTag(i);
            Panel_piao.addTouchEventListener(function(sender, type){
                if (mo.gameHelper.getIsTouchEnd(type)) {
                    mo.kwxCardHelper.setUserSelectPiao(sender.getTag());
                }
            }, this);
        }

        this.loadUI();

        this.setVisible(false);
    },

    onEnter : function(){
        this._super();
        this.updatePiaoSelect();
        mo.eventHelper.add("gameSelectPiaoUpdate", this, function(){
            this.updatePiaoSelect();
        });
    },

    onExit : function(){
        mo.eventHelper.remove(this);
        this._super();
    },

    updatePiaoSelect : function(){
        var selectIndex = mo.kwxCardHelper.selectPiaoIndex;
        for (var i = 0; i < 3; i++){
            var Panel_piao = mo.seekWidgetByName(this.Panel_piao, "Panel_piao" + i);
            var Image_check = mo.seekWidgetByName(Panel_piao, "Image_check");
            Image_check.loadTexture(selectIndex == i ? "res/ccs/table/btn/check_select1.png" : "res/ccs/table/btn/check_select0.png");
        }
    },

    loadUI : function(){
        for (var i = 0; i < 3; i++){
            var Panel_player = mo.seekWidgetByName(this.ccsNode, "Panel_player" + i);
            this.Panel_players.push(Panel_player);
        }
    },

    setVisible : function(isVisible){
        this.unschedule(this.updateEndInfo);
        this._super(isVisible);

        if (isVisible){
            this.Panel_piao.setVisible(mo.kwxTable.mTableConfig.piao != 0);
        }
    },

    setEndInfo : function(roundEndInfo, isReconnet){
        this.mRoundEndInfo = roundEndInfo;

        var delayTime = 0;
        if (isReconnet != undefined && isReconnet == true){
            //如果是黄庄要通知ui显示
            this.setHuangzhuangInfo();

            this.scheduleOnce(function(){
                this.updateEndInfo();
            }, delayTime);
        }else{
            if (mo.kwxTable.mPlayerType == 0){
                mo.seekWidgetByName(this.ccsNode, "Button_ok").setVisible(false);
                mo.seekWidgetByName(this.ccsNode, "Button_ok").setPositionX(0);
                var Image_textOk = mo.seekWidgetByName(mo.seekWidgetByName(this.ccsNode, "Button_ok"), "Image_text");
                mo.gameHelper.loadTextureImage(Image_textOk, "res/ccs/table/btn/text_fanhui.png");

                mo.seekWidgetByName(this.ccsNode, "Button_share").setVisible(true);
                mo.seekWidgetByName(this.ccsNode, "Button_share").setPositionX(-150);

                mo.seekWidgetByName(this.ccsNode, "Button_close").setVisible(true);

                //隐藏录像控件
                mo.kwxTable.mKwxReplayLayer.setVisible(false);
            }else{
                mo.seekWidgetByName(this.ccsNode, "Button_ok").setVisible(true);
                mo.seekWidgetByName(this.ccsNode, "Button_ok").setPositionX(150);
                var Image_textOk = mo.seekWidgetByName(mo.seekWidgetByName(this.ccsNode, "Button_ok"), "Image_text");
                mo.gameHelper.loadTextureImage(Image_textOk, "res/ccs/table/btn/text_queding.png");

                mo.seekWidgetByName(this.ccsNode, "Button_share").setVisible(true);
                mo.seekWidgetByName(this.ccsNode, "Button_share").setPositionX(-150);

                mo.seekWidgetByName(this.ccsNode, "Button_close").setVisible(false);
            }

            //如果是黄庄要通知ui显示
            this.setHuangzhuangInfo();

            //播放胡牌音效
            this.playEndEffect(roundEndInfo);

            //买马动画
            delayTime = mo.kwxTable.mKwxTableUILayer.mKwxTableMaimaLayer.startMaimaAction(roundEndInfo);

            this.scheduleOnce(function(){
                this.updateEndInfo();
            }, delayTime);
        }
    },

    updateEndInfo : function(){
        this.setVisible(true);
        var roundEndInfo = this.mRoundEndInfo;
        var CfgJson = JSON.parse(roundEndInfo.CfgJson);

        //包胡座位号
        var baohuSeat = this.getBaoHuViewSeat(roundEndInfo.MySeat - 1, roundEndInfo.RunTimeResult);

        //赢家座位号
        var winSeatView = -1;

        for (var seat = 0; seat < 3; seat++){
            var logicSeat = mo.kwxTableStatus.getLogicForView(seat, roundEndInfo.MySeat - 1);
            var seatUser = roundEndInfo["SeatUser" + (logicSeat + 1)];
            if (seatUser == null){
                this.Panel_players[seat].setVisible(false);
                continue;
            }
            this.Panel_players[seat].setVisible(true);

            //nick
            var Text_nick = mo.seekWidgetByName(this.Panel_players[seat], "Text_nick");
            mo.gameHelper.setTextString(Text_nick, seatUser.user_info.nickname);

            //uid
            var Text_uid = mo.seekWidgetByName(this.Panel_players[seat], "Text_uid");
            mo.gameHelper.setTextString(Text_uid, "用户id:" + seatUser.user_info.userid);
            Text_uid.setPositionX(Text_nick.getPositionX() + Text_nick.getContentSize().width + 5);
            Text_uid.setVisible(false);

            //head
            var Image_head = mo.seekWidgetByName(this.Panel_players[seat], "Image_head");
            mo.gameHelper.loadImageForUrl(Image_head, seatUser.user_info.faceUrl);

            //iszhuang
            var Image_zhuang = mo.seekWidgetByName(this.Panel_players[seat], "Image_zhuang");
            Image_zhuang.setVisible(seatUser.IsHost == true);

            //买马
            var maimaPosx = this.setMaiMa(seatUser, this.Panel_players[seat]);
            var maima = this.getMaimaScore(logicSeat);
            mo.gameHelper.setTextString(mo.seekWidgetByName(this.Panel_players[seat], "Text_maima"), maima + "");
            mo.seekWidgetByName(this.Panel_players[seat], "Text_maima").setPositionX(maimaPosx);

            //杠分
            var gangfen = this.getGangScore(logicSeat, roundEndInfo.RunTimeResult);
            mo.gameHelper.setTextString(mo.seekWidgetByName(this.Panel_players[seat], "Text_gangfen"), gangfen + "");

            //总分
            var Fnt_score = mo.seekWidgetByName(this.Panel_players[seat], "Fnt_zongfen");
            var allScore = 0;
            var ids = seatUser.LostWin.ItemTypes;
            var nums = seatUser.LostWin.ItemNums;
            allScore = mo.gameUserInfo.getItemNum(ids, nums, 0);
            var allfen = allScore;
            if (allfen >= 0){
                Fnt_score.setFntFile("res/ccs/commonEnd/winFnt.fnt");
                allfen = "+" + allfen;
            }else {
                Fnt_score.setFntFile("res/ccs/commonEnd/loseFnt.fnt");
            }
            Fnt_score.setString(allfen);

            //番数
            var fan = allScore - gangfen - maima;
            mo.gameHelper.setTextString(mo.seekWidgetByName(this.Panel_players[seat], "Text_fanshu"), fan + "");

            //是否胡了
            var Image_isHu = mo.seekWidgetByName(this.Panel_players[seat], "Image_isHu");
            var isHU = seatUser.WinCard != null && seatUser.WinCard != 0;
            var isZimo = (seatUser.WinCardSource === 0);
            if (isHU){
                winSeatView = seat;
                Image_isHu.setVisible(true);
                if (isZimo){
                    //自摸
                    mo.gameHelper.loadTextureImage(Image_isHu, "res/ccs/table/end/zimo.png");
                }else{
                    //胡
                    mo.gameHelper.loadTextureImage(Image_isHu, "res/ccs/table/end/hu2.png");
                }
            }else{
                Image_isHu.setVisible(false);

                //包胡
                if (seat == baohuSeat){
                    Image_isHu.setVisible(true);
                    mo.gameHelper.loadTextureImage(Image_isHu, "res/ccs/table/end/baohu.png");
                }

                //赔胡
                if (mo.gameHelper.findValueForArray(this.mHuangzhuangPeihuSeats, seat) != null){
                    Image_isHu.setVisible(true);
                    mo.gameHelper.loadTextureImage(Image_isHu, "res/ccs/table/end/peihu.png");
                }
            }

            //亮牌 和 胡发
            var multStr = "";
            if (seatUser.OpenTing){
                multStr += "亮牌 ";
            }
            multStr += this.getHuCardType(seatUser.WinType);

            //飘和坎
            if (seatUser.Piao != null && seatUser.Piao > 0){
                multStr += (" 飘X" + seatUser.Piao);
            }

            if (seatUser.Kan != null && seatUser.Kan > 0){
                multStr += (" 坎X" + seatUser.Kan);
            }

            //明杠和暗杠还有续杠情况说明
            multStr += this.getGangType(roundEndInfo, seatUser, logicSeat);

            mo.gameHelper.setTextString(mo.seekWidgetByName(this.Panel_players[seat], "Text_huType"), multStr);

            //翻开牌
            var Panel_card = mo.seekWidgetByName(this.Panel_players[seat], "Panel_card");
            Panel_card.removeAllChildren();

            var cardWidth = this.mCardWidth;
            var xOffset = cardWidth / 2;

            //开口牌
            for (var i = 0; i < seatUser.Groups.length; i++){
                var group = seatUser.Groups[i];
                for(var j = 0; j < group.Cards.length; j++){
                    var card = new KwxCard();
                    card.setCardNum(group.Cards[j]);
                    if (group.GroupType == 5 && j != 3){
                        card.setCardKind(0, 4);
                    }else{
                        card.setCardKind(0, 3);
                    }
                    card.setPosition(cc.p(xOffset, 0));

                    var scale = cardWidth / card.getContentSize().width;
                    card.setScale(scale);
                    Panel_card.addChild(card);

                    if (j == 3){
                        card.setPosition(cc.p(xOffset - cardWidth * 2, 8));
                    }else{
                        xOffset += cardWidth;
                    }
                }
                xOffset += 5;
            }

            if(seatUser.Groups.length > 0){
                // xOffset += 7;
            }

            //手牌
            var handCardNums = seatUser.HandCards;
            if (isZimo){
                //移除手牌中自摸的牌
                for (var i = 0; i < handCardNums.length; i++){
                    if (handCardNums[i] == seatUser.WinCard){
                        handCardNums.splice(i, 1);
                        break;
                    }
                }
            }
            handCardNums.sort();
            for (var i = 0; i < handCardNums.length; i++){
                var card = new KwxCard();
                card.setCardNum(handCardNums[i]);
                card.setCardKind(0, 3);
                var scale = cardWidth / card.getContentSize().width;
                card.setPosition(cc.p(xOffset, 0));
                card.setScale(scale);
                Panel_card.addChild(card);

                xOffset += cardWidth;
            }

            xOffset += 5;

            //胡的牌 自摸也加上
            if (isHU){
                var card = new KwxCard();
                card.setCardNum(seatUser.WinCard);
                card.setCardKind(0, 3);
                var scale = cardWidth / card.getContentSize().width;
                card.setPosition(cc.p(xOffset, 0));
                card.setScale(scale);
                Panel_card.addChild(card);
            }
        }

        //局数
        var jushu = "局数:" + (roundEndInfo.NowPlayerTimes + 1) + "/" + roundEndInfo.AllPlayerTimes;
        mo.gameHelper.setTextString(mo.seekWidgetByName(this.ccsNode, "Text_jushu"), jushu);

        //time
        var date = new Date();
        // var time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " ";
        // time += (date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds());
        mo.gameHelper.setTextString(mo.seekWidgetByName(this.ccsNode, "Text_time"), mo.gameHelper.getTimeYYMMDD(date));

        //播放音效
        this.playWinEffect(winSeatView);
    },

    playWinEffect : function(winSeat){
        if (winSeat == -1){
            //流局
            mo.soundHelper.playMjLiuju();
        }else{
            if (winSeat == 0){
                mo.soundHelper.playMjWin();
            }else{
                mo.soundHelper.playMjLose();
            }
        }
    },

    getGangScore : function(logicSeat, runTimeList){
        var result = 0;
        for (var i = 0; i < runTimeList.length; i++){
            var runtimeInfo = runTimeList[i];
            if (runtimeInfo.ToSeat == (logicSeat + 1)){
                if (runtimeInfo.ResultType == 1 ||
                    runtimeInfo.ResultType == 2 ||
                    runtimeInfo.ResultType == 3){
                    result += runtimeInfo.PayMoney;
                }
            }

            //扣掉的刚分也算上
            if (runtimeInfo.FromSeat == (logicSeat + 1)){
                if (runtimeInfo.ResultType == 1 ||
                    runtimeInfo.ResultType == 2 ||
                    runtimeInfo.ResultType == 3){
                    result -= runtimeInfo.PayMoney;
                }
            }
        }
        return result;
    },

    getHuCardType : function(WinType){
        var result = "";
        if (WinType == 0){
            //没有牌型
        }else{
            var winTypeStr = [
                "平胡",
                "对对胡",
                "清一色",
                "七对",
                "龙七对",
                "双龙七对",
                "大三元",
                "小三元",
                "明4归1",
                "暗4归1",
                "杠上开",
                "抢杠",
                "亮倒",
                "卡五星",
                "海底捞",
                "手抓一",
                "杠上炮"
            ];

            if(WinType == 4096){
                result += ("平胡 ");
            }

            for (var i = 0; i < winTypeStr.length; i++){
                var temp = Math.pow(2, i);
                if ((temp & WinType) != 0 && i != 12){
                    result += (winTypeStr[i] + " ");
                }
            }
        }
        return result;
    },

    //返回自己杠的情况
    getGangType : function(roundEndInfo, seatUser, logicSeat){
        var result = "";

        //自己手上的杠
        var minggangCount = 0, angangCount = 0, xugangCount = 0;
        for (var i = 0; i < seatUser.Groups.length; i++){
            if (seatUser.Groups[i].GroupType == 4){
                minggangCount++;
            }else if (seatUser.Groups[i].GroupType == 5){
                angangCount++;
            }else if (seatUser.Groups[i].GroupType == 6){
                xugangCount++;
            }
        }
        if (minggangCount != 0){
            result += (" 明杠X" + minggangCount);
        }
        if (angangCount != 0){
            result += (" 暗杠X" + angangCount);
        }
        if (xugangCount != 0){
            result += (" 续杠X" + xugangCount);
        }

        //别被人杠
        var otherminggang = 0, otherangang = 0, otherxugang = 0;
        for (var i = 0; i < roundEndInfo.RunTimeResult.length; i++){
            var resultKwx = roundEndInfo.RunTimeResult[i];
            if (resultKwx.FromSeat != (logicSeat + 1)){
                continue;
            }

            if (resultKwx.ResultType == 1){
                otherminggang++;
            }else if (resultKwx.ResultType == 2){
                otherangang++;
            }else if (resultKwx.ResultType == 3){
                otherxugang++;
            }
        }

        if (otherminggang != 0){
            result += (" 放杠X" + otherminggang);
        }
        if (otherangang != 0){
            result += (" 被暗杠X" + otherangang);
        }
        if (otherxugang != 0){
            result += (" 被续杠X" + otherxugang);
        }

        //上楼状态
        var config = JSON.parse(this.mRoundEndInfo.CfgJson);
        if (config.ruleid == 3 && config.sl == 1){
            if (this.mRoundEndInfo.BasePoint > 1){
                result += (" 上楼X" + this.mRoundEndInfo.BasePoint);
            }
        }

        return result;
    },

    getBaoHuViewSeat : function(myLogicSeat, runTimeList){
        var seat = -1;
        for (var i = 0; i < runTimeList.length; i++){
            var runtimeInfo = runTimeList[i];
            if (runtimeInfo.ResultType == 4 && runtimeInfo.BaoHuseat != null){
                var baohuLogicSeat = runtimeInfo.BaoHuseat;
                seat = mo.kwxTableStatus.getViewForLogic(baohuLogicSeat - 1, myLogicSeat);
            }
        }
        return seat;
    },

    getPeiHuViewSeat : function(myLogicSeat, runTimeList){
        var seats = [];
        for (var i = 0; i < runTimeList.length; i++){
            var runtimeInfo = runTimeList[i];
            if (runtimeInfo.ResultType == 5 && runtimeInfo.FromSeat != null){
                var peihuLogicSeat = runtimeInfo.FromSeat;
                seat = mo.kwxTableStatus.getViewForLogic(peihuLogicSeat - 1, myLogicSeat);
                seats.push(seat);
            }
        }
        return seats;
    },

    setHuangzhuangInfo : function(){
        var roundEndInfo = this.mRoundEndInfo;

        var isHuangzhuang = true;
        for (var seat = 0; seat < 3; seat++) {
            var logicSeat = mo.kwxTableStatus.getLogicForView(seat, roundEndInfo.MySeat - 1);
            var seatUser = roundEndInfo["SeatUser" + (logicSeat + 1)];
            if (seatUser == null){
                continue;
            }

            var isHU = seatUser.WinCard != null && seatUser.WinCard != 0;
            if (isHU){
                isHuangzhuang = false;
            }
        }

        if (isHuangzhuang){
            //通知ui显示
            mo.kwxTable.mKwxTableUILayer.mKwxTableResultLayer.showHuangzhuang();

            //如果黄庄赔 找到赔胡的玩家座位号
            this.mHuangzhuangPeihuSeats = this.getPeiHuViewSeat(roundEndInfo.MySeat - 1, roundEndInfo.RunTimeResult);
        }else{
            this.mHuangzhuangPeihuSeats = [];
        }
    },

    setMaiMa : function(seatUser, panel){
        var Panel_maima = mo.seekWidgetByName(panel, "Panel_maima");
        Panel_maima.setVisible(false);
        var result = Panel_maima.getPositionX() + 20;
        var scale = 1;
        var xStart = 0;


        if (seatUser == null){
            return result;
        }

        if (seatUser.Horses.length > 0) {
            result -= 5;
            var isSingletong = seatUser.Horses.length == 1;
            if (isSingletong){
                scale = 0.3;
                result += mo.kwxCardHelper.inhandCardSize.width * scale;
            }else{
                scale = 0.2;
                result += mo.kwxCardHelper.inhandCardSize.width * scale * 3;
                xStart = 0;
            }

            Panel_maima.removeAllChildren();
            Panel_maima.setVisible(true);
            var Panel_maimaHeight = Panel_maima.getContentSize().height;

            //中的马
            var maimaZhongNums = mo.kwxCardHelper.getMaimaZhong(seatUser.Horses, seatUser.WinCard);

            //加载精灵
            for (var i = 0; i < seatUser.Horses.length; i++) {
                var cardNum = seatUser.Horses[i];
                var card = new KwxCard();
                card.setCardNum(cardNum);
                card.setCardKind(0, 3);
                card.setAnchorPoint(0, 0.5);
                card.setScale(scale);
                if (mo.gameHelper.findValueForArray(maimaZhongNums, cardNum) == null) {
                    card.setCardColor(cc.color(128, 128, 128));
                }

                Panel_maima.addChild(card);

                if (isSingletong){
                    card.setPosition(cc.p(xStart, Panel_maimaHeight / 2));
                }else{
                    var x, y;
                    var row = i % 3;
                    var col = parseInt(i / 3);
                    x = row * mo.kwxCardHelper.inhandCardSize.width * scale;
                    y = (col == 0 ? Panel_maimaHeight / 4 : Panel_maimaHeight * 3 / 4);

                    card.setPosition(cc.p(xStart + x, y));
                }
            }
        }

        return result;
    },

    //播放胡牌音效
    playEndEffect : function(roundEndInfo){
        for (var i = 0; i < 3; i++){
            var seatUser = roundEndInfo["SeatUser" + (i + 1)];
            if (seatUser == null){
                continue;
            }

            //记录胡牌相关
            var isHU = seatUser.WinCard != null && seatUser.WinCard != 0;
            if (isHU){
                var isZimo = seatUser.WinCardSource == 0;
                var winType = seatUser.WinType;
                var sex = seatUser.user_info.sex;

                mo.soundHelper.playHuType(sex, isZimo, winType);
                break;
            }
        }
    },

    //返回用户买马分数
    getMaimaScore : function(logicSeat){
        //如果胡牌的玩家买马数据不为null 赢的玩家分数是HorseRate * 几个玩家 输的玩家是HorseRate
        //建立在 有且只有HorseRate不为null时 他是买马赢的人

        var maimaNum = -1;
        var winSeat = 0;
        var playerCount = 0;
        for (var i = 0; i < 3; i++){
            var seatUser = this.mRoundEndInfo["SeatUser" + (i + 1)];
            if (seatUser != null){
                playerCount++;

                if (seatUser.HorseRate != null && seatUser.HorseRate > 0){
                    maimaNum = seatUser.HorseRate;
                    winSeat = i;
                }
            }
        }

        if (maimaNum != -1){
            if (logicSeat == winSeat){
                return maimaNum * (playerCount - 1);
            }else{
                return -maimaNum;
            }
        }else{
            return 0;
        }
    }
});